package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import entity.User;

@WebFilter(filterName ="LoginFilter",urlPatterns = "/*")

public class LoginFilter implements Filter {
    public LoginFilter() {

    }
    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("enter filter");
        HttpServletRequest req= (HttpServletRequest)request;
        System.out.println("==========="+req.getServletPath());
        System.out.println(req.getServletPath());
        //	非法登录拦截
        if(req.getServletPath().equals("/login.jsp")||req.getServletPath().equals("/login.do")||req.getServletPath().equals("/register.jsp")||req.getServletPath().equals("/register.do")){

        }
        else {
            User user = (User) req.getSession().getAttribute("user");
            System.out.println("------------");
            if (user == null){
                System.out.println("被拦截");
                request.getRequestDispatcher("login.jsp").forward(request, response);
                return;
            }
        }
        //调用下一个过滤器，如果过滤器不存在，则直接访问jsp或servlet等资源
        chain.doFilter(request, response);
        System.out.println("leave filter");
    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
